﻿//========================================
// All rights reserved (C) 2017-2100
// CLR 版本：	4.0.30319.42000
// 命名空间:	SFJDService
// 文 件 名：	TransportSend
// 作    者：	WooG
// 联系方式：	wooglle@163.com
// 创建时间：	2018/6/17 15:00:27
//========================================
using Common;
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace SFJDService.TransportHandle
{
    class TransportSend
    {
        static int listenPort;

        Guid transGuid;
        static int maxLenght = PacketFileTransport.FileByteCount;

        public TransportSend(Guid guidTrans,string ip, int[] ports, int listeningPort)
        {
            if (Runtime.onSending)
            {
                return;
            }
            else
            {
                transGuid = guidTrans;
                listenPort = listeningPort;
                SendThreads.SetPorts(ip, ports);
                Handle();
            }
        }

        private void Handle()
        {
            Listeing();
            StartSend();
        }

        private void Listeing()//监听端口
        {
            new Thread(() =>
            {
                IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, listenPort);
                Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                IPEndPoint iep = new IPEndPoint(IPAddress.Any, listenPort);
                socket.Bind(iep);
                EndPoint ep = iep;
                while (true)
                {
                    try
                    {
                        byte[] buff = new byte[PacketFileTransport.BytesCount];
                        socket.ReceiveFrom(buff, ref ep);
                        SendThreads.CheckHandle(new PacketFileCheck(buff));
                    }
                    catch (Exception e)
                    {
                        throw new Exception(e.ToString());
                    }
                }
            }).Start();
        }

        private void SendFile(string fullPath, int fileIndex)
        {
            FileStream fs = new FileStream(fullPath, FileMode.Open, FileAccess.Read);
            int indexTotal = (int)(fs.Length / maxLenght);
            int index = 0;
            try
            {
                long fileLen = fs.Length;                        // 文件长度
                long leftLen = fileLen;                            // 未读取部分
                int readLen = 0;                                // 已读取部分
                byte[] buffer = null;

                if (fileLen <= maxLenght)
                {
                    buffer = new byte[fileLen];
                    readLen = fs.Read(buffer, 0, (int)fileLen);
                    PacketFileTransport packet = new PacketFileTransport(fileIndex, index, indexTotal, buffer);
                    SendThreads.Send(packet);
                    index++;
                }
                else
                {
                    while (leftLen > 0)
                    {
                        if (leftLen < maxLenght)
                        {
                            buffer = new byte[leftLen];
                            readLen = fs.Read(buffer, 0, Convert.ToInt32(leftLen));
                        }
                        else
                        {
                            buffer = new byte[maxLenght];
                            readLen = fs.Read(buffer, 0, maxLenght);
                        }
                        PacketFileTransport packet = new PacketFileTransport(fileIndex, index, indexTotal, buffer);
                        SendThreads.Send(packet);
                        index++;
                        leftLen -= readLen;
                    }
                }
            }
            catch
            {
                throw;
            }
            finally
            {
                fs.Flush();
                fs.Close();
            }
        }

        private void StartSend()
        {
            ClassTransportInfo transInfo = null;
            while ((transInfo = Runtime.xmlUpload.GetTransInfo(transGuid)).RootPath == null) { }
            Runtime.Printf("         FileSend读取XML完成");
            for(int i = 0; i < transInfo.Files.Count; i++)
            {
                string fileFullPath = transInfo.RootPath + transInfo.Files[i].RelativePath;//获取文件的完整路径
                string[] buf1 = transInfo.RootPath.Split('\\');
                string lastFolderName = buf1[buf1.Length - 2];//获取文件列表中所有文件的总文件夹名
                //SendFile(fileFullPath, lastFolderName + '\\' + file.RelativePath);
                SendFile(fileFullPath, i);
            }
            Runtime.Printf("文件发送成功。。");////换位置 线程等待
        }
    }
}
